import { getLayoutProps } from "@/common/layout/getProps";
import { ProForm } from "@/components/ProForm";
import { data } from "./data";
import { PlusOutlined } from "@ant-design/icons";
import { PageContainer } from "@ant-design/pro-layout";
import { Button, Divider, Form, Input, message, Modal, Row, Select, Table, type TableColumnsType, Pagination } from "antd";
import { useRouter } from "next/navigation";
import { useState,useEffect } from "react";
import { http } from "@/utils/request";


type TableDataType = Record<string, any>;

const EmployeeVoice = () => {
  const router = useRouter();
  const [form] = Form.useForm()
  const [list, setList] = useState([]);
  const [pageNum,setPageNum] = useState(1);
  const [pageSize,setPageSize] = useState(10);
  const [total,setTotal] = useState();
  console.log(data)
  const [editForm] = Form.useForm()
  const [open, setOpen] = useState<boolean>(false);
  const [currentEdit, setCurrentEdit] = useState<Partial<TableDataType>>({});

  const columns: TableColumnsType<TableDataType> = [
    {
      align: "center",
      title: "序号",
      width: 60,
      key: "index",
      render: (_text, _record, index) => {
        return index + 1
      }
    },
    {
      align: "center",
      title: "建议标题",
      dataIndex: "suggestionName"
    },
    {
      align: "center",
      title: "问题类型",
      dataIndex: "issueName"
    },
    {
      align: "center",
      title: "建议内容",
      dataIndex: "content"
    },
    {
      align: "center",
      title: "员工姓名",
      dataIndex: "personName"
    },
    {
      align: "center",
      title: "人员编码",
      dataIndex: "personId"
    },
    {
      align: "center",
      title: "状态",
      dataIndex: "status",
      render: (_, record) => {
        return (
          <>
            {record.status === "0" && <span>保存</span>}
            {record.status === "1" && <span>已提交</span>}
            {record.status === "2" && <span>已答复</span>}
          </>
        )
      }
    },
    {
      align: "center",
      title: "提交时间",
      dataIndex: "submitTime"
    },
    {
      align: "center",
      title: "操作",
      render: (_, record, index) => {
        return (
          <>
            <Button type={'link'} onClick={() => {
              router.push(`/employeeVoices/employeeVoicesDetail?id=${record.id}&type=detail`)
            }}>详情</Button>
            <Button type={'link'} onClick={() => {
              router.push(`/employeeVoices/employeeVoicesEdit?id=${record.id}`)
            }}>编辑</Button>
            <Button type={'link'} onClick={() => {
              viewReplies(record)
              setOpen(true);
            }}>查看回复</Button>
            {record.status === '1' ? <Button type={'link'} onClick={() => {
              Modal.confirm({
                title: "提示",
                content: "此操作将撤回该条记录，是否继续？",
                onOk(){
                  withdraw(record);
                }
              })
            }}>撤回</Button> : null}
            <Button type={'link'} danger onClick={() => {
              Modal.confirm({
                title: "提示",
                content: "此操作将永久删除该条记录，是否继续？",
                onOk(){
                  removeData(record.id);
                }
              })
            }}>删除</Button>
          </>
        )
      }
    }
  ]

  const handleOk = () => {
    setOpen(false);
  }

  const handleCancel = () => {
    setOpen(false);
  }
  //查询接口
  const getList = async() =>{
    try {
      const res = await http.get({
        url:'/PmPersonOpinion/qryList',
        params:{
          personName:form.getFieldValue('personName'),
          status:form.getFieldValue('status'),
          suggestionName:form.getFieldValue('suggestionName'),
          pageSize:pageSize,
          pageNum:pageNum
        }
      })
      setList(res.rows);
      console.log(res)
    } catch (errorInfo) {
      console.log(errorInfo);
    }
  }
  // 查看回复
  const viewReplies = async(data: object) => {
    try {
      const res = await http.post({
        url: "/PmPersonOpinion/selectAnswer",
        params:{
          opinionId:data.id
        },
      })
      if(res.code == 200){
        setCurrentEdit({
          field3: res.msg
        })
        // message.success('新增成功')
      }else{
        message.error(res.msg);
      }
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  }

  // 删除
  const removeData = async(id: string) => {
    try {
      const res = await http.delete({
        url:'/PmPersonOpinion/remove',
        params:{
          opinionId:id
        }
      })
      if(res.code == 200){
        message.success('删除成功')
        getList();
      }else{
        message.error(res.msg);
      }
    } catch (errorInfo) {
      console.log(errorInfo);
    }
  }
  // 撤回
  const withdraw = async(data: object) => {
    try {
      const res = await http.put({
        url:'/PmPersonOpinion/withdraw',
        data:data,
      })
      if(res.code == 200){
        message.success('撤回成功')
        getList();
      }else{
        message.error(res.msg);
      }
    } catch (errorInfo) {
      console.log(errorInfo);
    }
  }
  useEffect(()=>{
    getList();
  },[pageNum,pageSize])
  //修改页码或分页大小
  const changePagination = async (page: number, size: number)=>{
    setPageNum(page);
    if(size!==pageSize){
      setPageNum(1);
    }
    setPageSize(size);
  }
  return (
    <PageContainer>
      <ProForm form={form} layout={'inline'}  onSearch={getList} onReset={getList}>
        <Form.Item
          label={'标题'}
          name="suggestionName"
        >
          <Input placeholder="请输入" />
        </Form.Item>
        <Form.Item
          label={'员工姓名'}
          name="personName"
        >
          <Input placeholder="请输入" />
        </Form.Item>
        <Form.Item name="status" label={'状态'} >
          <Select placeholder="请选择状态" style={{width:'180px'}} options={[
            { value: '0', label: '保存' },
            { value: '1', label: '已提交' },
            { value: '2', label: '已答复' },
          ]} />
        </Form.Item>
      </ProForm>

      <Divider className={'my-[20px]'}></Divider>

      <Row className={'mb-[20px]'}>
        <Button type={'primary'} icon={<PlusOutlined />} onClick={() => {
          router.push(`/employeeVoices/employeeVoicesCreate`)
        }}>申请</Button>
      </Row>

      <Table
        dataSource={list}
        columns={columns}
        rowKey={(record) => `${record.id}`}
        pagination={false}
      ></Table>
      <Pagination
        className={'m-[20px] text-end'}
        current={pageNum}
        pageSize={pageSize}
        total={total}
        showSizeChanger
        showQuickJumper
        showTotal={(total) => `共 ${total} 条`}
        onChange={changePagination}
      />
      <Modal
        open={open}
        title="消息通知"
        afterClose={() => editForm.resetFields()}
        onOk={handleOk}
        onCancel={handleCancel}
        okText={'提交'}
        cancelText={'取消'}
        footer={(_, { OkBtn, CancelBtn }) => (
          <>
            <CancelBtn />
            <OkBtn />
          </>
        )}
      >
        <Form disabled form={editForm} initialValues={currentEdit} labelCol={{span: 4}}>
          <Form.Item
            name={'field3'}
          >
            <Input.TextArea rows={5} placeholder={"请输入"}></Input.TextArea>
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  )
}

export const getServerSideProps = getLayoutProps;
export default EmployeeVoice;
